{    
Indicator:      _FxDeviation.RS

Description:    Plots the deviation of Price relative to reference function, 
                such as: AMA, EMA, Linear Regression curve, Tilson T3 average,
                Jurik moving average, or a constant value.

                Indicator can be smoothed or rounded to nearest tradable value.
                  
                Check formatting Load Additional Data with 1 bar, to ensure Dev calculates immediately
                when RS loads.  If not checked, Dev will calculate when 1st real data tick arrives after
                RS is loaded.

Provided By:    MarkSanDiego

Updated:        09/09/08    original version
                12/25/10    StdDevLength and StdErrLength set to LRLength if not specified
                11/28/11    clean up code
                12/16/12    calculating functions without offset provides greater flexibility in using indicator with both historical and real data   

}
  
Input:     
    Price(close), 
    RefPrice(AvgPrice), 
    RefSmooth(0),
    Offset(6),

    RefID(3),                           { reference function identifier }
    AMALength(15),                      { arithmetic moving average length }
    EMALength(15),                      { exponential moving average length }
    LRLength(120),                      { linear regression function length }
//    LRTgtBar(-6),                     { linear regression function target bar, always set to negative of offset }
    KAMA_EffRatioLen(7),                { Kaufman adaptive moving average parameters }
    KAMA_FastLength(2),                 { Kaufman adaptive moving average parameters }
    KAMA_SlowLength(25),                { Kaufman adaptive moving average parameters }
    T3Length(20),                       { Tilson T3 moving average length }
    JMALength(20),                      { Jurik moving average length }
    JMAPhase(0),                        { Jurik moving average phase parameter }
    __VWAP("No parameter - RefID = 7"),
    RefValue(0),                        { define zero deviation to be this fixed value }

    DevID(2),                           { deviation function identifier }
    StdDevLength(0),                    { standard deviation length }
    StdErrLength(0),                    { standard error length }
    ATRLength(14),                      { average true range length }
    JATRLength(14),                     { percentage }
    Percent(1),                         { points }     
    Pts(1),
    UseAlertColors(true),               { color code deviation from price, according to defined deviation alerts }
    Dev1Alert(1.5),
    Dev2Alert(2.0),
    Dev3Alert(2.5),
    Dev4Alert(3.0),
    DevLevelMin(0),                     { 0 = ignore, otherwise display only DevLevel specified by range DevLevelMin to DevLevelMax  }
    DevLevelMax(0),                     { 0 = ignore, otherwise display only DevLevel specified by range DevLevelMin to DevLevelMax  }
    int CalcSeconds(5);                 { minimum seconds delay between calculations }

Vars: 
    Intrabarpersist count(0),           { Calculations count }
    Intrabarpersist BS(0),              { Bar Status }
    intrabarpersist bool Calc(true),    { true if calculation should be performed }
    Intrabarpersist Length(0),
    intrabarpersist LastBar(false),
    intrabarpersist oRef(0),
    Intrabarpersist oRef2(0),
    intrabarpersist oDev(0),  
    intrabarpersist oUnitdev(0),
    Intrabarpersist oUnitDev2(0),
    intrabarpersist oLRSlope(0),
    Intrabarpersist oLRSlope2(0),
    intrabarpersist oLRAngle2(0),
    intrabarpersist oLRIntercept2(0),
    Intrabarpersist DevLevel(0),
    Intrabarpersist ROC(0),
    intrabarpersist xOffset(Offset),    { user specified offset subsequently modified by code in this routine }
    Intrabarpersist RTData(false),      { true, if real time data }
    L1(0),                              { adjusted standard deviation length }
    L2(0),                              { adjust standard error length }
    intrabarpersist PlotColor(white),
    intrabarpersist PlotBGColor(black);

{ Methods begin //////////////////////////////////////////////////////////////////////////////////////////////////// }

var: elsystem.Timer Timer1( NULL );

Method override void InitializeComponent()
begin
    Timer1 = new elsystem.Timer;
    Timer1.Interval = CalcSeconds * 1000;
    Timer1.AutoReset = true;
    Timer1.Enable = true;
    Timer1.Name = "Timer1";
    Timer1.elapsed += Timer1_Elapsed;  
end;
 
{ run once every CalcSeconds seconds}
{The Elapsed event handler is called when the timer counts down to zero}
Method void Timer1_Elapsed( elsystem.Object sender, elsystem.TimerElapsedEventArgs args ) 
begin 
     //BS = -1;            { all timer generated executions associated with BarStatus(1) = -1 (undefined) }
    Calc = true;        
end;


{
Method  :       _FxDeviationMethod() 

Description:    This method calculates the unit deviation from a defined reference.

                In general, this method should be called only during BarStatus(1) = 2 conditions
                as the result values only change once per bar

Provided By:    Mark J. Krisburg

Modified:       12/16/11    original version
                

RefID:          (0) RefPrice (input RefPrice without averaging )
                (1) Simple Moving Average 
                (2) Exponential Moving Average 
                (3) Linear Regression 
                (4) T3 Average
                (5) Jurik Moving Average
                (6) Reference Value 

DevID:          (0) Raw deviation without further processing 
                (1) Standard Deviations ( Param=SDLength )
                (2) Standard Error ( Parm = SELength )
                (3) AvgTrueRange ( Param=ATRLength )
                (4) JMA True Range ( ATR using Juric moving average )
                (5) Percent
                (6) Points

}

          
Method void FxDeviation()
begin    
    
    switch RefID begin  
        Case 0:
            oRef2 = RefPrice;
        Case 1:
            oRef2 = Average(RefPrice, AMALength);
        Case 2:
            oRef2 = XAverage(RefPrice, EMALength);
        Case 3:
            value1 = _LinearRegFaster( RefPrice, LRLength, -Offset, oLRSlope2, oLRAngle2, oLRIntercept2, oRef2) ;    { LRTgrBar = -xOffset }            
        Case 4:
            oRef2 = AdaptiveMovAvg(RefPrice,  KAMA_EffRatioLen, KAMA_FastLength, KAMA_SlowLength);
        Case 5:
            oRef2 = T3Average.series(RefPrice, T3Length);
        
        // uncomment the next two lines if you have purchased Jurik Moving Average functions
//        Case 6:    
//            oRef2 = JRC.JMA.2K(RefPrice, JMALength, JMAPhase);
        Case 7:
            oRef2 = _VWAP;
        Case 8:
            oRef2 = RefValue;
    end;

 
     Once Begin
         switch DevID begin
             Case 1:
                 { StdDev Length must be > 1.  If not specified, use LRLength }
                 L1 = MaxList(2, iff(StdDevLength > 0, StdDevLength, LRLength));
            Case 2:
                { StdErr Length must be > 1.  If not specified, use LRLength }
                L2 = MaxList(2, iff(StdErrLength > 0, StdErrLength, LRLength));     
         end;    
     end;
 
 
    switch DevID begin
        Case 0:                    
            oUnitDev2 = 1;            { raw deviation without processing }
        Case 1:
            oUnitDev2 = _StdDev(RefPrice, L1);
        Case 2:
            oUnitDev2 = _StdError(RefPrice, L2);
        Case 3:
            oUnitDev2 = _AvgTrueRange(ATRLength);
        
        // uncomment the next two lines if you have purchased Jurik Moving Average functions
//        case 4:
//            oUnitDev2 = _JMATrueRange(JATRLength);
        Case 5:
            oUnitDev2 = RefPrice * Percent / 100; 
        Case 6:
            oUnitDev2 = Pts;
    end;
 
 end;   


Method void Calculations()
    begin
    
        Calc = false;
        Count = Count + 1;
    
        oRef = oRef2[Offset];
        oUnitdev = oUnitDev2[Offset];
        oLRSlope = oLRSlope2[Offset];
    
        { calculate each tick }
        if oUnitDev <> 0 then oDev = (Price - oRef)/oUnitDev;
        if oRef <> 0 then ROC = oLRSlope / oRef ;                            { future rate of change per bar in % }    
    
    
        { alerts }
        If UseAlertColors then begin
        
            switch oDev begin
                        
                case >= Dev4Alert:
                    DevLevel = 4;
                    PlotColor = black;
                    PlotBGColor = green;            
                Case >= Dev3Alert:
                    DevLevel = 3;
                    PlotColor = green;    
                    PlotBGColor = black;        
                Case >= Dev2Alert:
                    DevLevel = 2;
                    PlotColor = black;
                    PlotBGColor = red;            
                Case >= Dev1Alert:
                    DevLevel = 1;
                    PlotColor = red;
                    PlotBGColor = black;    
                                    
                Case <= - Dev4Alert:
                    DevLevel = -4;
                    PlotColor = black;
                    PlotBGColor = red;
                Case <= -Dev3Alert:
                    DevLevel = -3;
                    PlotColor = red;
                    PlotBGColor = black;
                Case <= -Dev2Alert:
                    DevLevel = -2;
                    PlotColor = black;
                    PlotBGColor = green;
                Case <= -Dev1Alert:
                    DevLevel = -1;
                    PlotColor = green;
                    PlotBGColor = black;
                                                                                                                                    
                Default:
                    DevLevel = 0;
                    PlotColor = lightgray;                                                
        
            end;
                    
        end;            
    
    end;        { Method Calculations }


Method void Plotter()
    begin
        
        plot1(Length, "Len", yellow);
        plot2(Offset, "xOff");
        plot3(-Offset, "Tgt");
        plot4(oDev,"Dev");
        plot5(ROC, "ROC");       
         
 {}        
        { debug - may comment these out, or hide outputs using indicator Formatting }
        plot18(oRef, "oRef");
        plot19(oUnitDev, "UnitDev");       
        plot24(Date[Offset], "Date[xOff]");
        plot25(Price, "Price");    
        plot26(CalcSeconds, "Calc Sec");    
        plot27(count, "Count");        
        plot28(BS, "BS");         
         
         
        SetPlotBGColor(1, blue);       
        SetPlotColor(4, PlotColor);
        SetPlotBGColor(4, PlotBGColor);
        
    end;    { Method Plotter }


{ Methods end   //////////////////////////////////////////////////////////////////////////////////////////////////// }


{ Begin Main program }


#region Main Program

    #region Tick Processing
    
        BS = BarStatus(1);
        
        #region Triggered Calculations
    
            { Calculate immediately if LastBarOnChart reached for real time data, since historical bars will set Calc = false each time after Calculation runs } 
            once (BS = 1) begin
                Calc = true;      
            end;

            { Calculations once every CalcSeconds during real time data }
            If Calc then begin  
                Calculations();        
            end;   
        
        #endregion;     
         
         
        #region Plotting
             
            If (DevLevelMin = 0 and DevLevelMax = 0) OR (oDev >= DevLevelMin AND oDev <= DevLevelMax) then begin    
                Plotter();        
            end;
        
        #endregion


    #endregion    { Tick Processing }


    #region EndOfBar Processing
    
        If BS = 2 then begin
            FxDeviation();
            Calc = true;
        end;        

    #endregion                             
                         
#endregion { Main Program }